package lm.concurrency.pattern.balking;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 8:49 2024/11/7
 */
@Slf4j
public class Demo {
    public static void main(String[] args) {
        Demo tpt = new Demo();
        tpt.start();
        tpt.start();
        tpt.start();

        /*Thread.sleep(3500);
        log.debug("停止监控");
        tpt.stop();*/
    }

    // 监控线程
    private Thread monitorThread;
    // 停止标记
    private volatile boolean stop = true;

    // 启动监控线程
    public void start() {
        if (!stop) { // false
            log.debug("不要重复执行");
            return;
        }
        synchronized (this) {
            if (!stop) { // false
                return;
            }
            stop = false;
        }
        monitorThread = new Thread(() -> {
            while (true) {
                if (stop) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                }
            }
        }, "monitor");
        monitorThread.start();
    }

    // 停止监控线程
    public void stop() {
        stop = true;
        monitorThread.interrupt();
    }
}
